package leetcode;

public class Leetcode8 {
    public int myAtoi(String str) {
        str = str.trim();
        if(str.length()==0){
            return 0;
        }
        boolean negetive = false;
        int index = 0;
        if(str.charAt(index)=='-'){
            negetive = true;
            index++;
        }else if(str.charAt(index)=='+'){
            index++;
        }else if(!Character.isDigit(str.charAt(index))){
            return 0;
        }
        int sum = 0;
        while(index<str.length()&&Character.isDigit(str.charAt(index))){
            int digit = str.charAt(index)-'0';
            if(sum>(Integer.MAX_VALUE-digit)/10){//查看越界情况
                if(negetive){
                    sum = Integer.MIN_VALUE;
                }else{
                    sum = Integer.MAX_VALUE;
                }
                break;
            }
            sum = sum*10+digit;
            index++;
        }
        return negetive ?-1*sum:sum;
    }
}
